//
//  YPDataBase.m
//  WHISPER
//
//  Created by lanou3g on 15/12/29.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YPDataBase.h"
#import "FMDB.h"
#import "YPSelectListModel.h"
#import "YPSelectWheelModel.h"
#import "YPUser.h"
#import "YPDynamicModle.h"
#import "YPFramentModel.h"

@implementation YPDataBase

static FMDatabase *dataBase = nil;

+ (void)initialize{
    if (self == [YPDataBase class]) {
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *filePath = [path stringByAppendingPathComponent:@"WHISPER.sqlite"];
        dataBase = [[FMDatabase alloc]initWithPath:filePath];
        [dataBase open];
        [dataBase executeUpdate:@"create table if not exists t_select (id integer primary key autoincrement not null,select_data data);"];
        [dataBase executeUpdate:@"create table if not exists t_dynamic (id integer primary key autoincrement not null,dynamic_data data);"];
       [dataBase executeUpdate:@"create table if not exists t_frament (id integer primary key autoincrement not null,frament_data data);"];
        [dataBase close];
    }
}

- (void)insertDataWithSelectDic:(NSDictionary *)dic success:(void (^)())success fail:(void (^)(NSError *))fail{
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    [dataBase open];
    NSData *data = [self returnDataWithDictionary:dic name:@"select"];
    BOOL flag = [dataBase executeUpdate:@"insert into t_select (select_data) values (?);",data];
        if (!flag) {
            NSError *err = [NSError errorWithDomain:@"插入数据失败" code:205 userInfo:nil];
            fail(err);
        }else{
          success();
        }
    [dataBase close];
}

- (void)insertDataWithDynamicDic:(NSDictionary *)dic success:(void (^)())success fail:(void (^)(NSError *))fail{
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    [dataBase open];
        NSData *data = [self returnDataWithDictionary:dic name:@"dynamic"];
        BOOL flag = [dataBase executeUpdate:@"insert into t_dynamic (dynamic_data) values (?);",data];
        if (!flag) {
            NSError *err = [NSError errorWithDomain:@"插入数据失败" code:205 userInfo:nil];
            fail(err);
        }else{
            success();
        }
    [dataBase close];
}

- (void)insertDataWithFramentDic:(NSDictionary *)dic success:(void (^)())success fail:(void (^)(NSError *))fail{
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    [dataBase open];
    NSData *data = [self returnDataWithDictionary:dic name:@"frament"];
    BOOL flag = [dataBase executeUpdate:@"insert into t_frament (frament_data) values (?);",data];
    if (!flag) {
        NSError *err = [NSError errorWithDomain:@"插入数据失败" code:205 userInfo:nil];
        fail(err);
    }else{
        success();
    }
    [dataBase close];
}

- (void)getSelectDataFromDataBaseSuccess:(void (^)(NSArray*))list wheel:(void (^)())listwheel fail:(void (^)(NSError *))fail{
    [dataBase open];
    FMResultSet *listSet = [dataBase executeQuery:@"select select_data from t_select"];
    NSMutableArray *listArr = [NSMutableArray array];
    while ([listSet next]) {
        NSData *data = [listSet dataForColumn:@"select_data"];
        NSDictionary *dic = [self returnDictionaryWithData:data name:@"select"];
        for (NSDictionary *dataDic in dic[@"data"][@"list"]) {
            YPSelectListModel *model = [[YPSelectListModel alloc]init];
            model.imglist = @[].mutableCopy;
            [model setValuesForKeysWithDictionary:dataDic];
            if ([model.name isEqualToString:@"音乐"]) {
                model.coverimg = @"http://pkimg.image.alimmdn.com/upload/20151216/d1999d7e4d7f81b28f2bc3a961c98580.png";
            }
            model.userinfo = [[YPUser alloc]init];
            [model.userinfo setValuesForKeysWithDictionary:dataDic[@"userinfo"]];
            [listArr addObject:model];
        }
    }
    if (listArr.count < 1) {
        NSError *err = [NSError errorWithDomain:@"读取数组失败" code:205 userInfo:nil];
        fail(err);
    }else{
        list(listArr);
            listwheel();
    }
    [dataBase close];
}

- (void)getDynamicDataFromDataBaseSuccess:(void (^)(NSArray*))success fail:(void (^)(NSError *))fail{
    [dataBase open];
    FMResultSet *listSet = [dataBase executeQuery:@"select dynamic_data from t_dynamic"];
    NSMutableArray *listArr = [NSMutableArray array];
    while ([listSet next]) {
        NSData *data = [listSet dataForColumn:@"dynamic_data"];
        NSDictionary *dic = [self returnDictionaryWithData:data name:@"dynamic"];
        for (NSDictionary *tempDic in dic[@"data"][@"list"]) {
            YPDynamicModle *modle = [[YPDynamicModle alloc]init];
            [modle setValuesForKeysWithDictionary:tempDic];
            modle.userinfo = [[YPUser alloc]init];
            [modle.userinfo setValuesForKeysWithDictionary:tempDic[@"userinfo"]];
            modle.counterList = [[YPCounterListModle alloc]init];
            [modle.counterList setValuesForKeysWithDictionary:tempDic[@"counterList"]];
            modle.userinfos = @[].mutableCopy;
            for (NSDictionary *dic in tempDic[@"userinfos"]) {
                YPUser *user = [[YPUser alloc]init];
                [user setValuesForKeysWithDictionary:dic];
                [modle.userinfos addObject:user];
            }
            [listArr addObject:modle];
        }
    }
    if (listArr.count < 1) {
        NSError *err = [NSError errorWithDomain:@"读取数组失败" code:205 userInfo:nil];
        fail(err);
    }else{
        success(listArr);
    }
    [dataBase close];
}
- (void)getFramentDataFromDataBaseSuccess:(void (^)(NSArray*))success fail:(void (^)(NSError *))fail{
    [dataBase open];
    FMResultSet *listSet = [dataBase executeQuery:@"select frament_data from t_frament"];
    NSMutableArray *listArr = [NSMutableArray array];
    while ([listSet next]) {
        NSData *data = [listSet dataForColumn:@"frament_data"];
        NSDictionary *dic = [self returnDictionaryWithData:data name:@"frament"];
        for (NSDictionary *tempDic in dic[@"data"][@"list"]) {
            YPFramentModel *model = [[YPFramentModel alloc]init];
            [model setValuesForKeysWithDictionary:tempDic];
            [listArr addObject:model];
        }
    }
    if (listArr.count < 1) {
        NSError *err = [NSError errorWithDomain:@"读取数组失败" code:205 userInfo:nil];
        fail(err);
    }else{
        success(listArr);
    }
    [dataBase close];
}

- (void)deleteSelectSuccess:(void (^)())success fail:(void (^)(NSError *))fail{
    [dataBase open];
    BOOL flag = [dataBase executeUpdate:@"delete from t_select"];
    if (!flag) {
        NSError *err = [NSError errorWithDomain:@"插入数据失败" code:205 userInfo:nil];
        fail(err);
    }else{
        success();
    }
    [dataBase close];
}
- (void)deleteDynamicSuccess:(void (^)())success fail:(void (^)(NSError *))fail{
    [dataBase open];
    BOOL flag = [dataBase executeUpdate:@"delete from t_frament"];
    if (!flag) {
        NSError *err = [NSError errorWithDomain:@"插入数据失败" code:205 userInfo:nil];
        fail(err);
    }else{
        success();
    }
    [dataBase close];
}
- (void)deleteFramentSuccess:(void (^)())success fail:(void (^)(NSError *))fail{
    [dataBase open];
    BOOL flag = [dataBase executeUpdate:@"delete from t_select"];
    if (!flag) {
       NSError *err = [NSError errorWithDomain:@"插入数据失败" code:205 userInfo:nil];
        fail(err);
    }else{
        success();
    }
    [dataBase close];
}

- (NSData*)returnDataWithDictionary:(NSDictionary*)dict name:(NSString*)name{
    NSMutableData* data = [[NSMutableData alloc]init];
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:dict forKey:name];
    [archiver finishEncoding];
    return data;
}

- (NSDictionary*)returnDictionaryWithData:(NSData *)data name:(NSString*)name{
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    NSDictionary* myDictionary = [unarchiver decodeObjectForKey:name];
    [unarchiver finishDecoding];
    return myDictionary;
}

@end
